#include "util_tools.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
#include <stdint.h>
#include <sstream>
#include <iomanip>

#include "thirdparty/cjson/cJSON.h"
#include "string_match.h"


std::string GetSysTimeString( void )
{
    time_t rawtime;
    time( &rawtime );

    return TimeToString(rawtime);
}

std::string TimeToString(time_t rawtime)
{
    struct tm * tm = localtime( &rawtime );

    std::ostringstream os;
    os << std::setfill('0')
       << std::setw(4) << tm->tm_year+1900
       << "-"
       << std::setw(2) << tm->tm_mon+1
       << "-"
       << std::setw(2) << tm->tm_mday
       << " "
       << std::setw(2) << tm->tm_hour
       << ":"
       << std::setw(2) << tm->tm_min
       << ":"
       << std::setw(2) << tm->tm_sec;

    return os.str();
}

// 获取时间字符串，tm为空时获取当前时间字符串
std::string GetTimeString(struct tm *tm )
{
    if (tm == nullptr) {
        time_t rawtime;
        time( &rawtime );
        tm = localtime( &rawtime );
    }

    std::ostringstream os;
    os << std::setfill('0')
       << std::setw(4) << tm->tm_year+1900
       << "-"
       << std::setw(2) << tm->tm_mon+1
       << "-"
       << std::setw(2) << tm->tm_mday
       << "T"
       << std::setw(2) << tm->tm_hour
       << ":"
       << std::setw(2) << tm->tm_min
       << ":"
       << std::setw(2) << tm->tm_sec
       << ".000+0800";

    return os.str();
}

// 获取时间戳，strTm为空时获取当前时间戳
time_t GetTimeStamp(std::string strTm)
{
    struct tm t;
    if (strTm == "")
    {
        return time( NULL );
    }
    sscanf(strTm.c_str(), "%d-%d-%dT%d:%d:%d", &t.tm_year, &t.tm_mon, &t.tm_mday, &t.tm_hour, &t.tm_min, &t.tm_sec);
    t.tm_year -= 1900;
    t.tm_mon -= 1;
    return mktime(&t);
}

std::string FloatToString(float k, float v)
{
    uint32_t Rate;
    static char buf[32] = {0};

    Rate = k * 10000;

    if(Rate >= 1000)
    {
        sprintf(buf, "%.1f", v);
    }
    else if(Rate >= 100)
    {
        sprintf(buf, "%.2f", v);
    }
    else if(Rate >= 10)
    {
        sprintf(buf, "%.3f", v);
    }
    else
    {
        sprintf(buf, "%.4f", v);
    }

    return buf;
}

std::string FloatToString(float v)
{
    std::string str = std::to_string(v);

    while (str.find_last_of('0') == (str.size() - 1))
    {
        str.pop_back();
    }
    if (str.find_last_of('.') == (str.size() - 1))
    {
        str.push_back('0');
    }

    return str;
}

std::string FloatToString(double v)
{
    static char buf[64] = {0};

    sprintf(buf, "%.6f", v);

    return buf;
}

std::string i32toa(int i)
{
    return std::to_string(i);
}

std::string u32toa(uint32_t i)
{
    return std::to_string(i);
}

std::string dtoa(double v)
{
    return std::to_string(v);
}

std::string i64toa(int64_t i)
{
    return std::to_string(i);
}

std::string u64toa(uint64_t i)
{
    return std::to_string(i);
}
